package com.woke.addressactivity;

import android.Manifest;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bean.VipLevel;
import com.bumptech.glide.Glide;
import com.example.woke.AddadressActivity;
import com.example.woke.ChannelActivateActivity;
import com.example.woke.InTheChannelListActivity;
import com.example.woke.MainActivity;
import com.http.HttpMethods;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.PersistentCookieStore;
import com.loopj.android.http.RequestParams;
import com.netease.nim.uikit.GlideApp;
import com.woke.data.Datas_usertypoe;
import com.woke.httpupload.FileProviderUtils;
import com.woke.method.MyApp;
import com.woke.serizedatas.Datas_load;
import com.wokeMy.view.turui.MyRealNameActivity;
import com.wokeMy.view.view.RoundImageView;
import com.zhongcai.online.R;

import org.apache.http.Header;
import org.apache.http.util.EncodingUtils;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import kankan.wheel.widget.OnWheelChangedListener;
import kankan.wheel.widget.WheelView;
import kankan.wheel.widget.adapters.ArrayWheelAdapter;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

public class UserinfoActivity extends BaseActivity implements OnClickListener,
        OnWheelChangedListener, EasyPermissions.PermissionCallbacks {

    private TextView mTchaname, mTaddress, mTphone;
    //            mTshanghu;
    private PopupWindow citypopupWindow;
    private ArrayList<area> list;
    private ArrayList<area> firstname;
    private ArrayList<area> secondname;
    public static final String ENCODING = "UTF-8";
    private TextView mTfinsh;
    private ProgressBar mBar;
    private MyApp myapp;
    private boolean turename = false;
    private boolean shanghu = false;
    private RoundImageView mIcon;
    private String feyanUsersId;
    private static final int PHOTO_CAPTURE = 0x11;//拍照
    private static final int PHOTO_PIC = 0x12;//相册
    private static final int PHOTO_CROP = 0x13;//裁剪

    private boolean zorf = false;
    private String actionUrl = HttpMethods.BASEURL + "g=api&m=user&a=userHead";
    private String photoTemp;
    private String photoName;
    Uri imageUri;
    private File tempFile;//裁剪后的图片
    private int dheight;
    private int dwidth;
    // private String newName = "";
    private boolean uploadsuess = false;
    private WheelView mViewProvince;
    private WheelView mViewCity;
    private WheelView mViewDistrict;
    private SharedPreferences sharep;
    private String dataString;
    private Myhotpreciver reciver;
    private AnimationDrawable mAnimationDrawable;
    private Handler mHandler = new Handler();
    TextView ewm;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_userinfo);
        EventBus.getDefault().register(this);

        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                .detectDiskReads().detectDiskWrites().detectNetwork()
                .penaltyLog().build());
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
                .detectLeakedSqlLiteObjects().penaltyLog().penaltyDeath()
                .build());

        sharep = getSharedPreferences("loaduser", Context.MODE_PRIVATE);


        firstname = new ArrayList<area>();
        list = new ArrayList<area>();
        secondname = new ArrayList<area>();
        myapp = (MyApp) getApplication();
        intview();

        if (myapp.getDatas_load() != null) {
            String avatar = myapp.getDatas_load().getAvatar();
            if (!TextUtils.isEmpty(avatar)) {
                GlideApp.with(this)
                        .load("http://"
                                + myapp.getDatas_load().getAvatar())
                        .placeholder(R.mipmap.icn__launch_oem)
                        .error(R.mipmap.icn__launch_oem)
                        .into(mIcon);
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updataUserInfo(VipLevel vipLevel) {

        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (myapp != null && myapp.getDatas_load() != null) {
                    mTlevel.setText(myapp.getDatas_load().vipdescribe);
                }
            }
        }, 1000);
    }

    @Override
    protected void onResume() {
        super.onResume();
//        Merchantstype();
        initRealNameState();
    }

    private void initRealNameState() {
        if (myapp.getDatas_load() == null) return;
        if (myapp.getDatas_load().getUser_no_status().equals("1")) {
            mTchaname.setText("未认证");
            turename = false;
        } else if (myapp.getDatas_load().getUser_no_status().equals("2")) {
            mTchaname.setText("待审核");
            turename = false;
        } else if (myapp.getDatas_load().getUser_no_status().equals("3")) {
            mTchaname.setText("已认证");
            turename = true;
        }
    }

    @Override
    protected void onDestroy() {

        EventBus.getDefault().unregister(this);
        unregisterReceiver(reciver);
        super.onDestroy();
    }

    private static final int CAMERA = 88;

    @AfterPermissionGranted(CAMERA)
    private void methodRequiresTwoPermission() {
        String[] perms = {Manifest.permission.CAMERA};
        if (EasyPermissions.hasPermissions(this, perms)) {
            photo();
        } else {
            // Do not have permissions, request them now
            EasyPermissions.requestPermissions(this, "需要读取本地文件/相机权限",
                    CAMERA, perms);
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        if (requestCode == CAMERA) {
            photo();
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        if (requestCode == CAMERA) {
            new AlertDialog.Builder(this).setMessage("请在<权限管理>里打开相机权限")
                    .setPositiveButton("前往", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                            intent.setData(Uri.fromParts("package", getPackageName(), null));
                            startActivity(intent);
                            dialog.dismiss();
                        }
                    })
                    .setNegativeButton("取消", null)
                    .create()
                    .show();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(Datas_usertypoe event) {
        String ssss = event.ssss;
        mTlevel.setText(ssss + "  ");
    }

    private TextView mTgphone;
    private View layout;
    private RelativeLayout mFrame;
    private LinearLayout mLiners;
    private TextView mTcanle;

    private TextView mTlevel;

    private void setUpData() {
        initProvinceDatas();
        mViewProvince.setViewAdapter(new ArrayWheelAdapter<String>(
                UserinfoActivity.this, mProvinceDatas));

        mViewProvince.setVisibleItems(7);
        mViewCity.setVisibleItems(7);
        mViewDistrict.setVisibleItems(7);
        updateCities();
        updateAreas();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (uploadsuess == true) {
                Intent intent = new Intent();
                intent.putExtra("newappimgeurl", photoName);
                setResult(659, intent);
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * ��ݵ�ǰ���У�������WheelView����Ϣ
     */
    private void updateAreas() {
        int pCurrent = mViewCity.getCurrentItem();
        mCurrentCityName = mCitisDatasMap.get(mCurrentProviceName)[pCurrent];
        String[] areas = mDistrictDatasMap.get(mCurrentCityName);

        if (areas == null) {
            areas = new String[]{""};
        }
        mViewDistrict
                .setViewAdapter(new ArrayWheelAdapter<String>(this, areas));
        mViewDistrict.setCurrentItem(0);
    }

    /**
     * ��ݵ�ǰ��ʡ��������WheelView����Ϣ
     */
    private void updateCities() {
        int pCurrent = mViewProvince.getCurrentItem();
        mCurrentProviceName = mProvinceDatas[pCurrent];
        String[] cities = mCitisDatasMap.get(mCurrentProviceName);
        if (cities == null) {
            cities = new String[]{""};
        }
        mViewCity.setViewAdapter(new ArrayWheelAdapter<String>(this, cities));
        mViewCity.setCurrentItem(0);
        updateAreas();
    }

    private void intview() {
        reciver = new Myhotpreciver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("com.woke.realnameavitivyt");
        registerReceiver(reciver, filter);

        findViewById(R.id.avuser_info_dresssur).setOnClickListener(this);
        mLiners = (LinearLayout) findViewById(R.id.avuserinfo_liner_adress);
        mLiners.setOnClickListener(this);
        layout = getLayoutInflater().inflate(R.layout.wheelpopupforcity, null);
        mFrame = (RelativeLayout) findViewById(R.id.avuserinfo_frame);
        mIcon = (RoundImageView) findViewById(R.id.avuserinfo_image_inco);
        mTgphone = (TextView) findViewById(R.id.avuserinfo_text_phone);
        if (myapp.getDatas_load() != null) {
            mTgphone.setText(myapp.getDatas_load().getUser_login());
        }
        findViewById(R.id.avuserinfo_image_back).setOnClickListener(this);
//        findViewById(R.id.avuserinfo_relati_add).setOnClickListener(this);
        mTchaname = (TextView) findViewById(R.id.avuserinfo_text_chinaname);
//        mTshanghu = (TextView) findViewById(R.id.avuserinfo_shanghu_chinaname);
        mTaddress = (TextView) findViewById(R.id.avuserinfo_text_address);
        mTlevel = (TextView) findViewById(R.id.avuserinfo_text_level);

        if (myapp.getDatas_load() != null) {
            mTlevel.setText(myapp.getDatas_load().vipdescribe);
        }
        if (null != myapp.getDatas_load() && null != myapp.getDatas_load().getProvince_id()
                && !myapp.getDatas_load().getProvince_id().equals("")) {
            mTaddress.setText(myapp.getDatas_load().getProvince_id() + "."
                    + myapp.getDatas_load().getCity_id() + "   ");
        }
        mTphone = (TextView) findViewById(R.id.avuserinfo_text_phone);
        findViewById(R.id.avuserinfo_relati_0).setOnClickListener(this);
        // findViewById(R.id.avuserinfo_relati_1).setOnClickListener(this);
        findViewById(R.id.avuserinfo_relati_2).setOnClickListener(this);
        findViewById(R.id.avuserinfo_relati_3).setOnClickListener(this);
        findViewById(R.id.avuserinfo_relati_4).setOnClickListener(this);
        findViewById(R.id.avuserinfo_relati_5).setOnClickListener(this);
        ewm=(TextView)findViewById(R.id.avuserinfo_relati_6);
        ewm.setOnClickListener(this);
        if (!getResources().getString(R.string.oem_app_name).equals("中财在线")){
            ewm.setVisibility(View.GONE);
        }

        findViewById(R.id.avuserinfo_relati_7).setOnClickListener(this);
//        findViewById(R.id.avuserinfo_relati_8).setOnClickListener(this);
        findViewById(R.id.avuserinfo_relati_9).setOnClickListener(this);
        findViewById(R.id.avuserinfo_relati_10).setOnClickListener(this);

        findViewById(R.id.in_the_list_layout).setOnClickListener(this);

        mViewProvince = (WheelView) findViewById(R.id.id_province);
        mViewCity = (WheelView) findViewById(R.id.id_city);
        mViewDistrict = (WheelView) findViewById(R.id.id_district);
        mTcanle = (TextView) findViewById(R.id.avuser_info_dressc);
        mTcanle.setOnClickListener(this);
        // ���change�¼�
        mViewProvince.addChangingListener(this);
        // ���change�¼�
        mViewCity.addChangingListener(this);
        // ���change�¼�
        mViewDistrict.addChangingListener(this);

        mTfinsh = (TextView) findViewById(R.id.avuserinfo_text_finish);
        mTfinsh.setOnClickListener(this);
        mBar = (ProgressBar) findViewById(R.id.avuserinfo_progre_bar);
        mAnimationDrawable = (AnimationDrawable) mBar.getIndeterminateDrawable();
        if (mAnimationDrawable != null) {
            mAnimationDrawable.stop();
        }
        setUpData();

    }

    class Myhotpreciver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {

            Bundle extras = intent.getExtras();
            photoName = extras.getString("feyanUsersIdr");
            int parent = extras.getInt("parent");
            if (null != photoName) {
                uploadcheckmap(photoName);
            }
        }
    }

    /* �ϴ��ļ���Server�ķ��� */
    private String uploadFile(String imageurldd) {
        if (myapp.getDatas_load() == null) return String.valueOf(false);
        System.out.print("正在发送请求！");
        String end = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        try {
            URL url = new URL(actionUrl + "&userid="
                    + myapp.getDatas_load().getId());
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setDoInput(true);
            con.setDoOutput(true);
            con.setUseCaches(false);
            con.setRequestMethod("POST");
            /* setRequestProperty */
            con.setRequestProperty("Connection", "Keep-Alive");
            con.setRequestProperty("Charset", "UTF-8");
            con.setRequestProperty("Content-Type",
                    "multipart/form-data;boundary=" + boundary);
            /* ����DataOutputStream */
            DataOutputStream ds = new DataOutputStream(con.getOutputStream());
            ds.writeBytes(twoHyphens + boundary + end);
            ds.writeBytes("Content-Disposition: form-data; "
                    + "name=\"file1\";filename=\"" + "zhongcai.jpg" + "\""
                    + end);
            ds.writeBytes(end);

//			Mapupload maplos = new Mapupload ();
//			Bitmap getimage = maplos.getimage (imageurldd, 100);
//			InputStream fStream = maplos.Bitmap2IS (getimage);
            InputStream fStream = new FileInputStream(photoName);
            /* ȡ���ļ���FileInputStream */
            /* ����ÿ��д��1024bytes */
            int bufferSize = 1024 * 10;
            byte[] buffer = new byte[bufferSize];
            int length = -1;
            /* ���ļ���ȡ����������� */
            while ((length = fStream.read(buffer)) != -1) {
                /* ������д��DataOutputStream�� */
                ds.write(buffer, 0, length);
            }
            ds.writeBytes(end);
            ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
            /* close streams */
            fStream.close();
            ds.flush();
//			/* ȡ��Response���� */
//			InputStream is = con.getInputStream ();
//			int ch;
//			StringBuffer b = new StringBuffer ();
//			while ((ch = is.read ()) != - 1) {
//				b.append ((char) ch);
//			}
//
//			String s = b.toString ();
            //开始获取数据
            BufferedInputStream bis = new BufferedInputStream(con.getInputStream());
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            int len;
            byte[] arr = new byte[1024];
            while ((len = bis.read(arr)) != -1) {
                bos.write(arr, 0, len);
                bos.flush();
            }
            bos.close();

            String substring = bos.toString("utf-8");
            JSONObject json = new JSONObject(substring);
            if (null != json.getString("flag")) {
                String string = json.getString("flag");
                Log.e("string", string);
                if (string.equals("success")) {
                    JSONObject object = json.getJSONObject("data");
                    final String data = object.getString("data");
                    // myapp.setusericon(data);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            GlideApp.with(UserinfoActivity.this)
                                    .load("http://" + data)
                                    .placeholder(R.mipmap.icn__launch_oem)
                                    .error(R.mipmap.icn__launch_oem)
                                    .into(mIcon);

                            if (myapp.getDatas_load() != null) {
                                myapp.getDatas_load().setAvatar(data);
                            }
                        }
                    });

                    uploadsuess = true;
                } else {
                    uploadsuess = false;
                }
            } else {
                uploadsuess = false;
            }

            ds.close();
        } catch (Exception e) {
            System.out.print("网络出现异常！");
            uploadsuess = false;
            e.printStackTrace();
        }
        return "" + uploadsuess;
    }


    private void showDialog(String mess) {
        new AlertDialog.Builder(UserinfoActivity.this).setTitle("提示")
                .setMessage(mess)
                .setNegativeButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                    }
                }).show();
    }

    private void photo() {

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (intent.resolveActivity(getPackageManager()) != null) {
            // Ensure that there's a camera activity to handle the intent
            File photo = FileProviderUtils.createImageFile(this);

            if (photo != null) {
                photoTemp = photo.getAbsolutePath();
//				imageUri = FileProvider.getUriForFile (this, "com.zhongcai.online.fileProvider", photo);
                imageUri = Uri.fromFile(photo);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                startActivityForResult(intent, PHOTO_CAPTURE);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PHOTO_PIC:
                    if (data != null && data.getData() != null) {
                        detailOnActivityResult(PHOTO_PIC, data.getData());
                    }
                    break;
                case PHOTO_CAPTURE:
                    detailOnActivityResult(PHOTO_CAPTURE, Uri.fromFile(new File(photoTemp)));
                    break;
                case PHOTO_CROP:
                    if (data != null && data.getData() != null) {
                        Log.e("Camera", "PHOTO_CROP  1");
                        detailOnActivityResult(PHOTO_CROP, data.getData());
                    } else {
                        Log.e("Camera", "PHOTO_CROP  2");
                        detailOnActivityResult(PHOTO_CROP, Uri.fromFile(tempFile));
                    }
                    break;
            }
        }

        if (requestCode == 123) {
            if (resultCode == 122) {
                turename = false;
                mTchaname.setText("待审核");
            }
        }

    }

    private void detailOnActivityResult(int requestCode, Uri uri) {
        switch (requestCode) {
            case PHOTO_CAPTURE:
                //拍照
                sendBroadcast(
                        new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
            case PHOTO_PIC:
                //选择图片
                //然后裁剪

                tempFile = FileProviderUtils.createImageFile(this);
                Log.e("cache", tempFile.getAbsolutePath());
//					Uri imageUriTemp = FileProvider.getUriForFile (this, "com.zhongcai.online.fileProvider", photo);
                Uri imageUriTemp = Uri.fromFile(tempFile);
                Log.e("cache uri", imageUriTemp.toString());

                Intent intent = new Intent("com.android.camera.action.CROP");
                intent.setDataAndType(uri, "image/*");
                intent.putExtra("crop", "true");
                intent.putExtra("scale", true);
                intent.putExtra("aspectX", 1);    // aspectX aspectY 是宽高的比例
                intent.putExtra("aspectY", 1);
                intent.putExtra("outputX", 200);// outputX outputY 是裁剪图片宽高
                intent.putExtra("outputY", 200);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUriTemp);
                intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
                intent.putExtra("noFaceDetection", true);
                intent.putExtra("return-data", true);
                startActivityForResult(intent, PHOTO_CROP);

                break;

            case PHOTO_CROP:
                //裁剪后,则上传图片
                GlideApp.with(this)
                        .load(uri)
                        .placeholder(R.mipmap.icn__launch_oem)
                        .error(R.mipmap.icn__launch_oem)
                        .into(mIcon);
                photoName = tempFile.toString();
                uploadcheckmap(photoName);
                break;
        }
    }

    private void uploadcheckmap(String photoName2) {
        if (mAnimationDrawable != null) {
            if (!mAnimationDrawable.isRunning()) {
                mAnimationDrawable.start();
            }
        }
        MyTask myTask = new MyTask();
        myTask.execute(photoName2);
    }

    class MyTask extends AsyncTask<String, Integer, String> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mFrame.setVisibility(View.VISIBLE);
        }

        @Override
        protected String doInBackground(String... params) {

            String uploadFile = uploadFile(photoName);
            return "" + uploadFile;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            int in = values[0];
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            if (result.equals("true")) {
                Toast.makeText(UserinfoActivity.this, "上传成功",
                        Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(UserinfoActivity.this, "上传失败",
                        Toast.LENGTH_SHORT).show();
            }
            mFrame.setVisibility(View.GONE);
            if (mAnimationDrawable != null) {
                if (mAnimationDrawable.isRunning()) {
                    mAnimationDrawable.stop();
                }
            }
        }
    }

    /**
     * ����û������ʱ���ʾ��ʽ�����ص�ǰʱ��ĸ�ʽ �����yyyyMMdd��ע����ĸy���ܴ�д��
     *
     * @param sformat yyyyMMddhhmmss
     * @return
     */
    public static String getUserDate(String sformat) {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat(sformat);
        String dateString = formatter.format(currentTime);
        return dateString;
    }

    public class PopupWindows extends PopupWindow {

        public PopupWindows(Context mContext, final int parent) {

            View view = View
                    .inflate(mContext, R.layout.item_popupwindows, null);
            view.startAnimation(AnimationUtils.loadAnimation(mContext,
                    R.anim.fade_ins));
            LinearLayout ll_popup = (LinearLayout) view
                    .findViewById(R.id.ll_popup);
            ll_popup.startAnimation(AnimationUtils.loadAnimation(mContext,
                    R.anim.push_bottom_in_2));

            setWidth(LayoutParams.FILL_PARENT);
            setHeight(LayoutParams.FILL_PARENT);
            setBackgroundDrawable(new BitmapDrawable());
            setFocusable(true);
            setOutsideTouchable(true);
            setContentView(view);
            showAtLocation(view, Gravity.BOTTOM, 0, 0);
            update();

            Button bt1 = (Button) view
                    .findViewById(R.id.item_popupwindows_camera);
            Button bt2 = (Button) view
                    .findViewById(R.id.item_popupwindows_Photo);
            Button bt3 = (Button) view
                    .findViewById(R.id.item_popupwindows_cancel);
            bt1.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        methodRequiresTwoPermission();
                    } else {
                        photo();
                    }
                    dismiss();
                }
            });
            bt2.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                    Intent i = new Intent(
                            Intent.ACTION_PICK,
                            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(i, PHOTO_PIC);
                    dismiss();
                }
            });
            bt3.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                    dismiss();
                }
            });
        }
    }

    private void sendcity(final String aa, final String bb) {
        if (myapp.getDatas_load() == null) return;
        AsyncHttpClient ahc = new AsyncHttpClient();
        PersistentCookieStore myCookieStore = new PersistentCookieStore(
                UserinfoActivity.this);
        ahc.setCookieStore(myCookieStore);
        RequestParams params = new RequestParams();
        params.put("g", "api");
        params.put("m", "user");
        params.put("a", "updateArea");
        params.put("province_id", aa);
        params.put("city_id", bb);
        params.put("user_id", myapp.getDatas_load().getId());
        ahc.get(HttpMethods.BASEURL, params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers,
                                  JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                try {
                    String flag = response.getString("flag");
                    if (flag.equals("success")) {
                        String string = response.getString("info");
                        Datas_load datas_load = myapp.getDatas_load();
                        datas_load.setProvince_id(aa);
                        datas_load.setCity_id(bb);
                        mTaddress.setText(aa + " " + bb + "  ");
                        Toast.makeText(UserinfoActivity.this, "" + string,
                                Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(UserinfoActivity.this, "修改失败！",
                                Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onStart() {
                // TODO Auto-generated method stub
                super.onStart();
                mTfinsh.setClickable(false);
                mTfinsh.setBackgroundResource(R.drawable.rect_lightgray);
                mBar.setVisibility(View.VISIBLE);
            }

            @Override
            public void onFailure(int statusCode, Header[] headers,
                                  String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                Toast.makeText(UserinfoActivity.this, "退出失败！",
                        Toast.LENGTH_SHORT).show();
                Log.e("response", "失败" + responseString);
            }

            @Override
            public void onFinish() {
                super.onFinish();
                mTfinsh.setClickable(true);
                mTfinsh.setBackgroundResource(R.drawable.rect_lightred);
                mLiners.setVisibility(View.GONE);
                mBar.setVisibility(View.GONE);
            }
        });
    }

    // ��assets �ļ����л�ȡ�ļ�����ȡ���
    public String getFromAssets(String fileName) {
        String result = "";
        try {
            InputStream in = getResources().getAssets().open(fileName);
            // ��ȡ�ļ����ֽ���
            int lenght = in.available();
            // ����byte����
            byte[] buffer = new byte[lenght];
            // ���ļ��е���ݶ���byte������
            in.read(buffer);
            result = EncodingUtils.getString(buffer, ENCODING);
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    private void finishcurrn() {
        AsyncHttpClient ahc = new AsyncHttpClient();
        PersistentCookieStore myCookieStore = new PersistentCookieStore(
                UserinfoActivity.this);
        ahc.setCookieStore(myCookieStore);
        RequestParams params = new RequestParams();
        params.put("g", "api");
        params.put("m", "user");
        params.put("a", "logout");
        ahc.get(HttpMethods.BASEURL, params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers,
                                  JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                try {
                    if (response != null) {
                        Log.e("logout", response.toString());
                    }
                    String flag = response.getString("flag");
                    if (flag.equals("success")) {
                        String string = response.getString("info");
                        Toast.makeText(UserinfoActivity.this, "" + string,
                                Toast.LENGTH_SHORT).show();
                        myapp.setDatas_load(null);
                        Intent intent = new Intent(UserinfoActivity.this,
                                MainActivity.class);
                        startActivity(intent);
                        Editor edit = sharep.edit();
                        edit.putString("load", "not");
                        edit.commit();
                        finish();
                    } else {
                        Toast.makeText(UserinfoActivity.this, "退出失败！",
                                Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onStart() {
                super.onStart();
                mTfinsh.setClickable(false);
                mTfinsh.setBackgroundResource(R.drawable.rect_lightgray);
                mFrame.setVisibility(View.VISIBLE);
            }

            @Override
            public void onFailure(int statusCode, Header[] headers,
                                  String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                Toast.makeText(UserinfoActivity.this, "退出失败！",
                        Toast.LENGTH_SHORT).show();
                Log.e("response", "失败" + responseString);
            }

            @Override
            public void onFinish() {
                super.onFinish();
                mTfinsh.setClickable(true);
                mTfinsh.setBackgroundResource(R.drawable.rect_lightred);
                mFrame.setVisibility(View.GONE);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.avuserinfo_image_back:
                finish();
                break;

            case R.id.avuserinfo_liner_adress:

                break;

            case R.id.avuserinfo_text_finish:
                finishcurrn();
                break;

            case R.id.avuserinfo_relati_0:
                new PopupWindows(UserinfoActivity.this, 0);
                break;

            case R.id.avuser_info_dresssur:
                sendcity(mCurrentProviceName, mCurrentCityName);
                break;

            case R.id.avuser_info_dressc:
                mLiners.setVisibility(View.GONE);
                break;

            case R.id.avuserinfo_relati_2:
                mLiners.setVisibility(View.VISIBLE);
                break;

            case R.id.avuserinfo_relati_4:
                Intent inten1t = new Intent(UserinfoActivity.this,
                        AddadressActivity.class);
                startActivity(inten1t);
                break;

            case R.id.avuserinfo_relati_5:
//                if (NetworkUtils.isConnected(this)) {
//                    Datas_load load = myapp.getDatas_load();
//                    if (load != null) {
//                        String userId = load.getId();
//                        if (!TextUtils.isEmpty(userId) && userId.matches("[0-9]*")) {
//                            HttpMethods.getInstance().getVipLevel(mVipLevelListObserver, Integer.parseInt(userId));
//                        }
//                    }
////                    Toast.makeText(UserinfoActivity.this,getResources().getString(R.string.oem_shengjiai),Toast.LENGTH_SHORT).show();
//                } else {
//                    showToast(getResources().getString(R.string.error_net2));
//                }
                String user_type=getResources().getString(R.string.usertype);
                if (myapp.getDatas_load().getUser_type().equals(user_type)){
                        Toast.makeText(UserinfoActivity.this,"您已经是"+getResources().getString(R.string.usertypeString),Toast.LENGTH_SHORT).show();
                }else {
                    //表示有可升级列表
                    startActivity(new Intent(UserinfoActivity.this, UpgradeMemberShipActivity.class));
                }
                break;

            case R.id.avuserinfo_relati_6:
                Intent inte2n1t1 = new Intent(UserinfoActivity.this,
                        Userinfo_erActivity.class);
                startActivity(inte2n1t1);
                break;

            case R.id.avuserinfo_relati_7:
                Intent intn1t1 = new Intent(UserinfoActivity.this,
                        Userinfo_xiaActivity.class);
                startActivity(intn1t1);
                break;

            case R.id.avuserinfo_relati_3:
                if (turename == true) {// 实名认证
                    Toast.makeText(this, "您已实名认证过了", Toast.LENGTH_SHORT).show();
                } else {
                    Datas_load load = myapp.getDatas_load();
                    if (load != null) {
                        if ("1".equals(load.getUser_no_status())) {
                            Intent intent = new Intent(UserinfoActivity.this,
                                    MyRealNameActivity.class);
                            startActivityForResult(intent, 123);
                        } else if ("2".equals(load.getUser_no_status())) {
                            new AlertDialog.Builder(this).setTitle("待审核")
                                    .setMessage("您的实名认证正在审核中,是否需重新提审核资料")
                                    .setPositiveButton("重新提交", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            Intent intent = new Intent(UserinfoActivity.this,
                                                    MyRealNameActivity.class);
                                            startActivityForResult(intent, 123);
                                        }
                                    })
                                    .setNegativeButton("取消", null)
                                    .create()
                                    .show();
                        } else if ("3".equals(load.getUser_no_status())) {
                            Toast.makeText(this, "您已经通过实名认证", Toast.LENGTH_SHORT).show();
                        } else {
                            Intent intent = new Intent(UserinfoActivity.this,
                                    MyRealNameActivity.class);
                            startActivityForResult(intent, 123);
                        }
                    }

                }
                break;
            case R.id.in_the_list_layout:
                //入驻列表
                if (myapp.getDatas_load() == null) return;
                if (null != myapp.getDatas_load().getUser_no_status()
                        && myapp.getDatas_load().getUser_no_status().equals("1")) {
                    new android.support.v7.app.AlertDialog.Builder(UserinfoActivity.this).setTitle("提示").setMessage("还未进行实名认证").setPositiveButton("去认证", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            Intent intent = new Intent(UserinfoActivity.this,
                                    MyRealNameActivity.class);
                            startActivityForResult(intent, 123);
                        }
                    }).setNegativeButton("取消", null).create().show();
                    Toast.makeText(UserinfoActivity.this, "还未进行实名认证",
                            Toast.LENGTH_SHORT).show();

                } else if (null != myapp.getDatas_load().getUser_no_status()
                        && myapp.getDatas_load().getUser_no_status().equals("2")) {
                    Toast.makeText(UserinfoActivity.this, "实名认证审核中，无操作权限",
                            Toast.LENGTH_SHORT).show();
                } else {
                    startActivity(new Intent(this, InTheChannelListActivity.class));
                }
                break;
            case R.id.avuserinfo_relati_9:
                Intent intent = new Intent(UserinfoActivity.this, UserpromoteActivity.class);
                startActivity(intent);
                break;
            case R.id.avuserinfo_relati_10:
//                Intent sk = new Intent(UserinfoActivity.this, MyShoukuanActivity.class);
//                startActivity(sk);
                Toast.makeText(UserinfoActivity.this,"暂未开通，敬请期待!",Toast.LENGTH_SHORT).show();
                break;
            default:
                break;
        }
    }

    private Observer<String> mSerialObserver = new Observer<String>() {
        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onNext(String serialNumber) {

            if (!TextUtils.isEmpty(serialNumber)) {
                Log.e("SerialNum", serialNumber);
                Datas_load datasLoad = MyApp.getInstance().getDatas_load();
                if (datasLoad != null) {
                    Intent intent = new Intent(UserinfoActivity.this, ChannelActivateActivity.class);
                    intent.putExtra("serialNum", serialNumber);
                    intent.putExtra("userId", Integer.parseInt(datasLoad.getId()));
                    startActivity(intent);
                }
            }
        }

        @Override
        public void onError(Throwable e) {

        }

        @Override
        public void onComplete() {

        }
    };

    @Override
    public void onChanged(WheelView wheel, int oldValue, int newValue) {
        // TODO Auto-generated method stub
        if (wheel == mViewProvince) {
            updateCities();
        } else if (wheel == mViewCity) {
            updateAreas();
        } else if (wheel == mViewDistrict) {
            mCurrentDistrictName = mDistrictDatasMap.get(mCurrentCityName)[newValue];
            mCurrentZipCode = mZipcodeDatasMap.get(mCurrentDistrictName);
        }
    }

    private Observer<List<VipLevel>> mVipLevelListObserver = new Observer<List<VipLevel>>() {
        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onNext(List<VipLevel> value) {
            if (value != null && value.size() > 0) {
                //表示有可升级列表
                startActivity(new Intent(UserinfoActivity.this, UpgradeMemberShipActivity.class));
            }
        }

        @Override
        public void onError(Throwable e) {
            if (e != null) {
                showToast(e.getMessage());
            }
        }

        @Override
        public void onComplete() {

        }
    };


    private void showToast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }
}
